<?php

namespace app\admin\controller\system;

use app\admin\controller\AuthController;
use app\model\system\SystemConfig;
use app\model\system\SystemConfigTab;
use albert\services\FormBuilder;
use albert\services\JsonService;
use albert\services\UtilService;
use Exception;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 配置管理类
 * Class ConfigTabController
 * @package app\admin\controller\system
 */
class ConfigTabController extends AuthController
{
    /**
     * 定义配置分类,需要添加分类可以手动添加
     * @return array
     */
    public function getConfigType(): array
    {
        return [
            ['value' => 0, 'label' => '系统'],
            ['value' => 1, 'label' => '应用'],
            ['value' => 2, 'label' => '支付'],
            ['value' => 3, 'label' => '其它']
        ];
    }

    /**
     * 基础配置
     * @return string
     * @throws Exception
     */
    public function index(): string
    {
        $where = UtilService::param([
            ['status', ''],
            ['title', ''],
            ['pid', 0],
        ], $this->request);
        $this->assign('where', $where);
        $this->assign(SystemConfigTab::getSystemConfigTabPage($where));
        return $this->fetch('system/config_tab/index');
    }

    /**
     * 添加
     * @return string
     * @throws Exception
     */
    public function create(): string
    {
        $f = [];
        $f[] = FormBuilder::select('pid', '父级分类', 0)->setOptions(SystemConfigTab::getTabTree())->filterable(1);
        $f[] = FormBuilder::input('title', '分类名称');
        $f[] = FormBuilder::input('eng_title', '分类字段英文');
        $f[] = FormBuilder::frameInputOne('icon', '图标', '/admin/widget/icon?fodder=icon')->icon('ionic')->height('500px');
        $f[] = FormBuilder::radio('type', '类型', 0)->options(self::getConfigType());
        $f[] = FormBuilder::radio('status', '状态', 1)->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]);
        $f[] = FormBuilder::number('sort', '排序', 0);
        $form = FormBuilder::make_post_form('添加分类配置', $f, '/admin/system/config/tab/save', 3);
        $form->setMethod('post')->setTitle('添加分类配置');
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 添加保存
     * Author: Albert3306
     * Date: 2021/6/29
     * @return string
     */
    public function save(): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['type', 0],
            ['sort', 0],
            ['icon', ''],
            ['title', ''],
            ['status', 1],
            ['eng_title', ''],
        ], $this->request);
        if (!$data['title']) return JsonService::fail('请输入按钮名称！');
        if (!$data['eng_title']) return JsonService::fail('请输入分类字段！');
        SystemConfigTab::create($data);
        return JsonService::successful('添加菜单成功!');
    }

    /**
     * 编辑
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function edit($id): string
    {
        $tab = SystemConfigTab::get($id)->getData();
        if (!$tab) return JsonService::fail('数据不存在！');
        $form = FormBuilder::create('/admin/system/config/tab/update/' . $id, [
            FormBuilder::select('pid', '父级分类', (string)$tab['pid'])->setOptions(SystemConfigTab::getTabTree())->filterable(1),
            FormBuilder::input('title', '分类名称', $tab['title']),
            FormBuilder::input('eng_title', '分类字段英文', $tab['eng_title']),
            FormBuilder::frameInputOne('icon', '图标', '/admin/widget/icon?fodder=icon', $tab['icon'])->icon('ionic')->height('500px'),
            FormBuilder::radio('type', '类型', $tab['type'])->options(self::getConfigType()),
            FormBuilder::radio('status', '状态', $tab['status'])->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]),
            FormBuilder::number('sort', '排序', $tab['sort'] ?? 0),
        ]);
        $form->setMethod('post')->setTitle('添加分类配置');
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 修改保存
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $id
     * @return string
     */
    public function update($id): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['type', 0],
            ['sort', 0],
            ['icon', ''],
            ['title', ''],
            ['status', 1],
            ['eng_title', ''],
        ], $this->request);
        if (!$data['title']) return JsonService::fail('请输入分类名称！');
        if (!$data['eng_title']) return JsonService::fail('请输入分类字段！');
        if (!SystemConfigTab::be($id)) return JsonService::fail('数据不存在！');
        SystemConfigTab::edit($data, $id);
        return JsonService::successful('修改成功！');
    }

    /**
     * 删除
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $id
     * @return string
     */
    public function delete($id): string
    {
        if (!$id) return JsonService::fail('参数有误！');
        if (SystemConfigTab::be(['pid' => $id])) return JsonService::fail('有子分类，不能直接删除!');
        if (!SystemConfigTab::del($id))
            return JsonService::fail(SystemConfigTab::getErrorInfo('删除失败,请稍候再试!'));
        else
            return JsonService::successful('删除成功!');
    }

    /**
     * 获取分类下的所有配置字段
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function sonConfig($id): string
    {
        $list = SystemConfig::getAll($id, 2);
        foreach ($list as $k => $v) {
            $list[$k]['value'] = json_decode($v['value'], true) ?: '';
            if ($v['type'] == 'radio' || $v['type'] == 'checkbox') {
                $list[$k]['value'] = SystemConfigTab::getRadioOrCheckboxValueInfo($v['menu_name'], $v['value']);
            }
            if ($v['type'] == 'upload' && !empty($v['value'])) {
                if ($v['upload_type'] == 1 || $v['upload_type'] == 3) $list[$k]['value'] = explode(',', $v['value']);
            }
        }
        return $this->fetch('system/config_tab/son_config', [
            'tab_id' => $id,
            'list'   => $list,
        ]);
    }
}